<?php

// +----------------------------------------------------------------------
// | ThinkPHP
// +----------------------------------------------------------------------
// | Copyright (c) 2008 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$

// 自动转换字符集 支持数组转换
function auto_charset($fContents, $from='gbk', $to='utf-8') {
    $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
    $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
    if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
        //如果编码相同或者非字符串标量则不转换
        return $fContents;
    }
    if (is_string($fContents)) {
        if (function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($fContents, $to, $from);
        } elseif (function_exists('iconv')) {
            return iconv($from, $to, $fContents);
        } else {
            return $fContents;
        }
    } elseif (is_array($fContents)) {
        foreach ($fContents as $key => $val) {
            $_key = auto_charset($key, $from, $to);
            $fContents[$_key] = auto_charset($val, $from, $to);
            if ($key != $_key)
                unset($fContents[$key]);
        }
        return $fContents;
    }
    else {
        return $fContents;
    }
}

/* 分类树 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = & $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] = & $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = & $refer[$parentId];
                    $parent[$child][] = & $list[$key];
                }
            }
        }
    }
    return $tree;
}

/* 排序 */

function sortBy($list, $field, $sortby = 'asc') {
    if (is_array($list)) {
        $refer = $resultSet = array();
        foreach ($list as $i => $data)
            $refer[$i] = &$data[$field];
        switch ($sortby) {
            case 'asc':
                asort($refer);
                break;
            case 'desc':
                arsort($refer);
                break;
            case 'nat':
                natcasesort($refer);
                break;
        }
        foreach ($refer as $key => $val)
            $resultSet[] = &$list[$key];
        return $resultSet;
    }
    return false;
}

/* 数组搜索 */

function search($list, $condition) {
    if (is_string($condition))
        parse_str($condition, $condition);
    $resultSet = array();
    foreach ($list as $key => $data) {
        $find = false;
        foreach ($condition as $field => $value) {
            if (isset($data[$field])) {
                if (0 === strpos($value, '/')) {
                    $find = preg_match($value, $data[$field]);
                } elseif ($data[$field] == $value) {
                    $find = true;
                }
            }
        }
        if ($find)
            $resultSet[] = &$list[$key];
    }
    return $resultSet;
}

/* 显示标签 */

function showTags($tags) {
    $tags = explode(' ', $tags);
    $str = '';
    foreach ($tags as $key => $val) {
        $tag = trim($val);
        $str .= ' <a href="' . __URL__ . '/tag/' . urlencode($tag) . '">' . $tag . '</a>  ';
    }
    return $str;
}

/* 内容处理 */

function getAbstract($content, $id) {
    if (false !== $pos = strpos($content, '[separator]')) {
        $content = substr($content, 0, $pos) . '  <P> (<a href="' . __URL__ . '/' . $id . '"><B>阅读全部内容… </B></a>) ';
    }
    return $content;
}

/* 处理内容 */

function removeAbstract($content) {
    return str_replace('[separator]', '', $content);
}

/* 处理大小 */

function getTitleSize($count) {
    $size = (ceil($count / 10) + 11) . 'px';
    return $size;
}

/* 颜色处理 */

function rcolor() {
    $rand = rand(0, 255);
    return sprintf("%02X", "$rand");
}

/* 颜色处理 */

function rand_color() {
    return '#' . rcolor() . rcolor() . rcolor();
}

/* 数据缓存 */

function cache($name, $value = '', $expire = 60) {
    if ('' === $value) {
        return xcache_get($name);
    } else {
        if (is_null($value)) {
            xcache_unset($name);
        } else {
            xcache_set($name, $value, $expire);
        }
    }
}

/* 主题管理 */

function getDefaultStyle($style) {
    if (empty($style)) {
        return 'blue';
    } else {
        return $style;
    }
}

/* 推荐 */

function getRecommend($type) {
    switch ($type) {
        case 1: $icon = '<IMG SRC="' . APP_PUBLIC_PATH . '/images/brand.gif" BORDER="0" align="absmiddle" ALT="">';
            break;
        default:
            $icon = '';
    }
    return $icon;
}

/* 密码处理 */

function pwdHash($password, $type = 'md5') {
    return hash($type, $password);
}

/* 生成不重复数 */

function build_count_rand($number, $length = 4, $mode = 1) {
    if ($mode == 1 && $length < strlen($number)) {
        return false;
    }
    $rand = array();
    for ($i = 0; $i < $number; $i++) {
        $rand[] = rand_string($length, $mode);
    }
    $unqiue = array_unique($rand);
    if (count($unqiue) == count($rand)) {
        return $rand;
    }
    $count = count($rand) - count($unqiue);
    for ($i = 0; $i < $count * 3; $i++) {
        $rand[] = rand_string($length, $mode);
    }
    $rand = array_slice(array_unique($rand), 0, $number);
    return $rand;
}

/* 时间格式化 */

function toDate($time, $format = 'Y-m-d H:i:s') {
    if (empty($time)) {
        return '';
    }
    $format = str_replace('#', ':', $format);
    return date(($format), $time);
}

/* 状态处理 */

function getStatus($status, $imageShow = true) {
    switch ($status) {
        case 0:
            $showText = '禁用';
            $showImg = '<IMG SRC="' . APP_PUBLIC_PATH . '/images/locked.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="禁用">';
            break;
        case 2:
            $showText = '待审';
            $showImg = '<IMG SRC="' . APP_PUBLIC_PATH . '/images/checkin.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="待审">';
            break;
        case -1:
            $showText = '删除';
            $showImg = '<IMG SRC="' . APP_PUBLIC_PATH . '/images/del.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="删除">';
            break;
        case 1:
        default:
            $showText = '正常';
            $showImg = '<IMG SRC="' . APP_PUBLIC_PATH . '/images/ok.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="正常">';
    }
    return ($imageShow === true) ? ($showImg) : $showText;
}

 function getNodeGroupName($gid){
 return M('group')->where("id='".$gid."'")->getField('title');
}

/* 状态显示 */

function showStatus($status, $id) {
    switch ($status) {
        case 0:$info = '<a href="__URL__/resume/id/'.$id.'" target="ajaxTodo">恢复</a>';
            break;
        case 2:$info = '<a href="__URL__/pass/id/'.$id.'" target="ajaxTodo">批准</a>';
            break;
        case 1:$info = '<a href="__URL__/forbid/id/'.$id.'" target="ajaxTodo">禁用</a>';
            break;
        case -1:$info = '<a href="__URL__/recycle/id/'.$id.'" target="ajaxTodo">还原</a>';
            break;
    }
    return $info;
}

/* 状态显示 */

function showRecommend($recommend, $id) {
    switch ($recommend) {
        case 0:$info = '<a href="javascript:recommend(' . $id . ')">推荐</a>';
            break;
        case 1:$info = '<a href="javascript:unrecommend(' . $id . ')">取消推荐</a>';
            break;
    }
    return $info;
}

/* 组名 */

function getGroupName($id) {
    if ($id == 0) {
        return '无上级组';
    }
    if ($list = F('groupName')) {
        return $list[$id];
    }
    $dao = D("Role");
    $list = $dao->field('id,name')->select();
    foreach ($list as $vo) {
        $nameList[$vo['id']] = $vo['name'];
    }
    $name = $nameList[$id];
    F('groupName', $nameList);
    return $name;
}

/* 显示文件扩展名 */

function showExt($ext, $pic = true) {
    static $_extPic = array(
'dir' => "folder.gif",
 'doc' => 'msoffice.gif',
 'rar' => 'rar.gif',
 'zip' => 'zip.gif',
 'txt' => 'text.gif',
 'pdf' => 'pdf.gif',
 'html' => 'html.gif',
 'png' => 'image.gif',
 'gif' => 'image.gif',
 'jpg' => 'image.gif',
 'php' => 'text.gif',
    );
    static $_extTxt = array(
'dir' => '文件夹',
 'jpg' => 'JPEG图象',
    );
    if ($pic) {
        if (array_key_exists(strtolower($ext), $_extPic)) {
            $show = "<IMG SRC='" . __ROOT__.'/Public' . "/Images/extension/" . $_extPic[strtolower($ext)] . "' BORDER='0' alt='' align='absmiddle'>";
        } else {
            $show = "<IMG SRC='" . __ROOT__.'/Public' . "/Images/extension/common.gif' WIDTH='16' HEIGHT='16' BORDER='0' alt='文件' align='absmiddle'>";
        }
    } else {
        if (array_key_exists(strtolower($ext), $_extTxt)) {
            $show = $_extTxt[strtolower($ext)];
        } else {
            $show = $ext ? $ext : '文件夹';
        }
    }

    return $show;
}

/* 处理文件大小 */

function byte_format($size, $dec = 2) {
    $a = array("B", "KB", "MB", "GB", "TB", "PB");
    $pos = 0;
    while ($size >= 1024) {
        $size /= 1024;
        $pos++;
    }
    return round($size, $dec) . " " . $a[$pos];
}

/* 置顶 */

function getTop($type) {
    switch ($type) {
        case 1: $icon = '<IMG SRC="' . APP_PUBLIC_PATH . '/images/top.gif" BORDER="0" align="absmiddle" ALT="">';
            break;
        default:
            $icon = '';
    }
    return $icon;
}

function getGoodsCategory(){
		$list=M('GoodsCategory')->select();
		$options=array(0=>'请选择');
		foreach($list as $item){
			$options[$item['id']]=$item['category_name'];
		}
		
		return $options;
}

function getGoodsBrand(){
		$list=M('GoodsBrand')->select();
		$options=array(0=>'请选择');
		foreach($list as $item){
			$options[$item['id']]=$item['brand_name'];
		}
		
		return $options;
}

function getCategoryName($cid){
	$Category=include(getCacheFilename('GoodsCategory'));
	return $Category[$cid]['category_name'];
}

function getBrandName($bid){
	$Brand=include(getCacheFilename('GoodsBrand'));
	return $Brand[$bid]['brand_name'];
}

function getUnit(){
		$options = array("块" => "块", "件" => "件","条" => "条","板" => "板","包" => "包","杯" => "杯","串" => "串","对" => "对");
		return $options;
}

function json_to_array($web){
$arr=array();
foreach($web as $k=>$w){
    if(is_object($w)) $arr[$k]=json_to_array($w); //判断类型是不是object
    else $arr[$k]=$w;
}
return $arr;
}

function get_items($json){
	$arr=array();
	//dump(json_decode($json));
	foreach(json_decode($json) as $k=>$w){
		$arr[]['id']=$w->id;
		$arr[]['product_name']=$w->id;
		$arr[]['product_code']=$w->id;
		$arr[]['price']=$w->id;
		$arr[]['number']=$w->id;
	}
}

function create_purchase($data){
	$html="<tr id=\"".$data['id']."\" class=\"product\"><td><span class=\"order\"></span></td><td>".$data['category']."</td><td>".$data['product_name']."</td><td>".$data['unit']."</td><td>".$data['product_code']."</td><td><input name=\"money\" value=\"".$data['purchase_price']."\" type=\"text\">元</td><td><input name=\"number\" value=\"\" type=\"text\"></td><td><input name=\"note\" value=\"\" type=\"text\"></td><td><input onclick=\"removeitem(".$data['id'].")\" value=\"移除条目\" type=\"button\"></td></tr>";
	return $html;
}

/* function get_stock_by_goodsid($goodsId,$store=0){
		$Stock=M('Stock');
		$map['goodsid']=$goodsId;
		$map['store']=$store;
		$vo=$Stock->where($map)->find();
		return $vo;
} */
/**
生成采购单编号
*/
function gen_purchase_number(){
	return C('companyname')."CGSQ".date('Ymdhms');
}

function get_purchase_status($st=0){
	switch ($st){
		case 0:
			return '未审批';
		case 1:
			return '已审批';
		case 2:
			return '未通过';			
	}	
}

function get_store_name($storeid){
	$arr=C('store');
	return $arr[$storeid][0];
}

function gen_report_number($type,$storeid=0){
	switch($type){
		case 'caigou':
			return C('companyname')."CGSQ".date('Ymdhms');
		case 'ruku':
			$arr=C('store');
			return C('companyname').$arr[$storeid][1]."RK".date('Ymdhms');
		case 'chuku':
			$arr=C('store');
			return C('companyname').$arr[$storeid][1]."CK".date('Ymdhms');
		default:
			$arr=C('store');
			return C('companyname').$arr[$storeid][1]."DF".date('Ymdhms');			
	}
}

/**
根据产品信息生成产品编号和产品条形码
*/
function gen_goods_code($goods){
	
	$goods['product_code']="1855".sprintf("%05d",$goods['brand']).sprintf("%08d",$goods['id']);
	$goods['barcode']=md5($goods['id']);
	
	return $goods;
 
}


function getCacheFilename($name) {
        return DATA_PATH . '~' . strtolower($name) . '.php';
}

?>